<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" @submit.prevent>
      <!-- 搜索表单字段修改为根据实体类的字段 -->
      <el-form-item label="街道地址" prop="streetAddress">
        <el-input
          v-model="queryParams.streetAddress"
          placeholder="请输入街道地址"
          clearable
          @keyup.enter="handleQuery"
          v-hasPermi="['htzj:jdgl:list']"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery" v-hasPermi="['htzj:jdgl:list']">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['htzj:jdgl:add']"
        >新增
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="streetList">
      <!-- 表格列修改为根据实体类的字段 -->
      <el-table-column label="街道ID" align="center" prop="streetId"/>
      <el-table-column label="街道地址" align="center" prop="streetAddress"/>
      <el-table-column label="街道办名称" align="center" prop="officeName"/>
      <el-table-column label="街道办地址" align="center" prop="officeAddress"/>
      <el-table-column label="街道办联系方式" align="center" prop="officeContact"/>
      <el-table-column label="街道二维码" align="center">
        <template #default="scope">
          <!-- 添加点击事件 -->
          <QrcodeVue :value="qrCodeUrl(scope.row.streetId)" :size="100" @click="showQrCode(scope.row.streetId)"/>
        </template>
      </el-table-column>
      <!-- 新增经度和纬度列 -->
      <el-table-column label="经度" align="center" prop="lng"/>
      <el-table-column label="纬度" align="center" prop="lat"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['htzj:jdgl:edit']"
          >修改
          </el-button>
          <el-button
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['htzj:jdgl:delete']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="streetFormRef" :model="form" :rules="rules" label-width="120px">
        <!-- 表单字段修改为根据实体类的字段 -->
        <el-form-item label="街道地址" prop="streetAddress">
          <el-input v-model="form.streetAddress" placeholder="请输入街道地址"/>
        </el-form-item>
        <el-form-item label="街道办名称" prop="officeName">
          <el-input v-model="form.officeName" placeholder="请输入街道办名称"/>
        </el-form-item>
        <el-form-item label="街道办地址" prop="officeAddress">
          <el-input v-model="form.officeAddress" placeholder="请输入街道办地址"/>
        </el-form-item>
        <el-form-item label="街道办联系方式" prop="officeContact">
          <el-input v-model="form.officeContact" placeholder="请输入街道办联系方式"/>
        </el-form-item>
        <!--        <el-form-item label="街道二维码" prop="qrCode">-->
        <!--          <el-input v-model="form.qrCode" placeholder="请输入街道二维码"/>-->
        <!--        </el-form-item>-->
        <!-- 替换原有的街道地理位置输入框为经度和纬度输入框 -->
        <el-form-item label="经度" prop="lng">
          <el-input v-model="form.lng" placeholder="请输入经度"/>
          <el-button type="text" @click="showMap = true">点击地图拾取</el-button>
        </el-form-item>
        <el-form-item label="纬度" prop="lat">
          <el-input v-model="form.lat" placeholder="请输入纬度"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 二维码放大 -->
    <el-dialog :title="qrCodeDialogTitle" v-model="qrCodeDialogVisible" width="500px" append-to-body>
      <div style="display: flex;justify-content: center;">
        <QrcodeVue :value="currentQrCodeUrl" :size="400" level="H"/>
      </div>
    </el-dialog>

    <!-- 地图弹窗 -->
    <el-dialog :title="'选择经纬度'" v-model="showMap" width="800px">
      <div id="map-container" style="width: 100%; height: 500px;"></div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="closeMap">确 定</el-button>
          <el-button @click="showMap = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, onUnmounted} from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader';
import {pageListStreet, delStreet, addStreet, updateStreet} from "@/api/htzj/streets";
import {ElMessage, ElMessageBox} from 'element-plus'
// 引入二维码组件
import QrcodeVue from 'qrcode.vue'

const loading = ref(false)
const total = ref(0)
const streetList = ref([])
const showSearch = ref(true)

const qrCodeUrl = (streetId) => {
  return `http://htjs.sxjzsy.com/${streetId}`;
}

const qrCodeDialogVisible = ref(false)
const qrCodeDialogTitle = ref('放大二维码')
const currentQrCodeUrl = ref('')

const showQrCode = (streetId) => {
  currentQrCodeUrl.value = qrCodeUrl(streetId)
  qrCodeDialogVisible.value = true
}

// 修改查询参数对象的属性名
const queryParams = ref({
  pageNum: 1, // 确保 pageNum 有默认值
  pageSize: 10,
  officeName: undefined
})

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

const resetQuery = () => {
  queryParams.value = {
    pageNum: 1, // 确保 pageNum 有默认值
    pageSize: 10,
    officeName: undefined
  };
  getList();
}

// 只保留一个 form 定义
const form = ref({
  streetId: undefined,
  streetAddress: undefined,
  officeName: undefined,
  officeContact: undefined,
  qrCode: undefined,
  lng: undefined,
  lat: undefined,
  // 新增街道办地址字段
  officeAddress: undefined
});

// 只保留一个 rules 定义
const rules = ref({
  officeName: [
    {required: true, message: "街道办名称不能为空", trigger: "blur"},
    {min: 2, max: 50, message: "街道办名称长度必须在 2 到 50 个字符之间", trigger: "blur"}
  ],
  streetAddress: [
    {required: false, message: "请输入街道地址", trigger: "blur"}
  ],
  officeAddress: [
    {required: false, message: "请输入街道办地址", trigger: "blur"}
  ],
  officeContact: [
    {required: false, message: "请输入街道办联系方式", trigger: "blur"}
  ],
  qrCode: [
    {required: false, message: "请输入街道二维码", trigger: "blur"}
  ],
  lng: [
    {required: false, message: "请输入经度", trigger: "blur"}
  ],
  lat: [
    {required: false, message: "请输入纬度", trigger: "blur"}
  ]
});

const getList = async () => {
  loading.value = true;
  try {
    const res = await pageListStreet(queryParams.value);
    if (res && res.rows && Array.isArray(res.rows)) {
      streetList.value = res.rows;
      total.value = res.total;
    } else {
      console.error('获取街道列表失败：返回数据格式不符合预期', res);
    }
  } catch (error) {
    console.error("获取街道列表失败", error);
  } finally {
    loading.value = false;
  }
}

// 只保留一个 submitForm 定义
const submitForm = () => {
  streetFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (form.value.streetId) {
          await updateStreet(form.value);
          ElMessage.success("修改成功");
        } else {
          await addStreet(form.value);
          ElMessage.success("新增成功");
        }
        open.value = false;
        getList();
      } catch (error) {
        console.error(error);
        ElMessage.error("操作失败");
      }
    }
  });
};

const handleDelete = (row) => {
  const streetId = row.streetId;
  ElMessageBox.confirm('是否确认删除该街道？', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(function () {
    return delStreet(streetId);
  }).then(() => {
    getList();
    ElMessage.success("删除成功");
  }).catch(() => {
  });
}

const open = ref(false);
const title = ref("");
const streetFormRef = ref();

const handleAdd = () => {
  reset();
  open.value = true;
  title.value = "添加街道";
};

const handleUpdate = (row) => {
  reset();
  const streetId = row.streetId;
  form.value = {...row};
  open.value = true;
  title.value = "修改街道";
};

const reset = () => {
  form.value = {
    streetId: undefined,
    streetAddress: undefined,
    officeName: undefined,
    officeContact: undefined,
    qrCode: undefined,
    lng: undefined,
    lat: undefined,
    // 重置街道办地址字段
    officeAddress: undefined
  };
  if (streetFormRef.value) {
    streetFormRef.value.resetFields();
  }
};

const cancel = () => {
  open.value = false;
  reset();
};

onUnmounted(() => {
  if (map) {
    map?.value.destroy()
  }
})
const map = ref(null);
const marker = ref(null);
const showMap = ref(false);

const initMap = async () => {
  try {
    window._AMapSecurityConfig = {
      securityJsCode: "a61305003e60660ffb8e4d2763bcc55f",
    };

    const AMap = await AMapLoader.load({
      key: 'd77e99299b7174a802d136190f717fe5',
      version: '2.0',
      plugins: ["AMap.Scale"]
    });

    // 在showMap变化时初始化地图
    watch(showMap, async (val) => {
      if (val && !map.value) {
        await nextTick();
        map.value = new AMap.Map('map-container', {
          zoom: 13,
          center: [107.03, 33.85],
          viewMode: '2D'
        });

        // 添加缩放控件
        map.value.addControl(new AMap.Scale());

        // 点击地图获取经纬度
        map.value.on('click', (e) => {
          form.value.lng = e.lnglat.lng.toFixed(6);
          form.value.lat = e.lnglat.lat.toFixed(6);
        });
      }
    });
  } catch (error) {
    console.error('地图加载失败:', error);
  }
}

// 监听经纬度变化
watch([() => form.value.lng, () => form.value.lat], ([lng, lat]) => {
  if (map.value && lng && lat) {
    // 清除原有标记
    if (marker.value) {
      marker.value.setMap(null);
    }
    // 创建新标记
    marker.value = new AMap.Marker({
      position: [lng, lat],
      map: map.value
    });
    // 调整地图视野
    map.value.setCenter([lng, lat]);
  }
}, {immediate: true});

// 关闭地图弹窗
const closeMap = () => {
  showMap.value = false;
}

onMounted(() => {
  getList();
  initMap();
})
</script>

<style scoped>
/* 添加地图容器样式 */
#map-container {
  width: 100%;
  height: 500px;
  min-height: 500px;
}

/* 其他原有样式 */
.mb8 {
  margin-bottom: 8px;
}

.dialog-footer {
  padding: 20px;
  text-align: right;
}
</style>
